const pathUtil = require('path');
const _ = require('lodash');
const {warn, error, highLight, right, filterMode, replaceDS} = require('../utils');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const MiniProgramPlugin = require('../miniprogram-plugin');

module.exports = (env) => {
	env = _.defaults(env, {
		mode:    'development',
		project: '',
	});
	env.mode = filterMode(env.mode);
	if (env.project === '')
		throw new Error('Unset project entry!');
	console.log(`entry mini-program ${error(env.project)} in ${warn(env.mode)}`);

	const root = process.cwd();
	const src = env.project;
	const dist = `${src}-dist`;
	const srcPath = pathUtil.resolve(root, src);

	let options = {debug: true};

	const distPathOf = (filename) => replaceDS(pathUtil.relative(srcPath, filename));

	// 默认的 loader
	const cssLoaders = [];

	if (env.project === 'example-2') {
		_.merge(options, {
			exts: {
				wxss: true,
			},
			app:  {
				files: false,
			},
		});
		// 要增加打包 wxss 的话，loaders要进行调整
		cssLoaders.push({
			test: /\.(wxss)$/,
			use:  {
				loader:  "file-loader",
				options: {
					name: distPathOf,
				},
			},
		});
	} else {
		options.mockMain = 'app.my.json';
		// 推荐的做法，将 css,wxss require(import) 到 js 中使用
		cssLoaders.push({
			test: /\.(css|wxss)$/,
			use:  [
				MiniCssExtractPlugin.loader,
				"css-loader",
			],
		});
	}

	return {
		mode:         env.mode,
		entry:        {
			app: [`./${src}/app.js`],
		},
		output:       {
			filename:      '[name].js',
			libraryTarget: 'var',
			path:          pathUtil.resolve(__dirname, dist),
		},
		target:       'node',
		module:       {
			rules: [
				{
					test: /\.(png|jpg)$/,
					use:  {
						loader:  "file-loader",
						options: {
							name: (filename) => {
								return replaceDS(pathUtil.relative(srcPath, filename));
							},
						},
					},
				},
				{
					test: /\.(json)$/,
					type: 'javascript/auto',
					use:  {
						loader:  "file-loader",
						options: {
							name: (filename) => {
								const path = replaceDS(pathUtil.relative(srcPath, filename));
								const reg = /app.(([a-z0-9-_]+).json)$/;
								if (path.match(reg)) {
									return path.replace(reg, 'app.json');
								}
								return path;
							},
						},
					},
				},
				{
					test: /\.(wxml)$/,
					use:  {
						loader:  "file-loader",
						options: {
							name: (filename) => {
								return replaceDS(pathUtil.relative(srcPath, filename));
							},
						},
					},
				},
				// 附加上 css 的 loaders
				...cssLoaders,
			],
		},
		plugins:      [
			new MiniProgramPlugin(src, dist, options),
			new MiniCssExtractPlugin(
				{
					filename: "[name].wxss",
				},
			),
		],
		devtool:      'inline',
		optimization: {
			splitChunks: {
				cacheGroups: {
					modules: {
						test:      /([\\/]node_modules[\\/])/,
						name:      'vendors',
						minSize:   0,
						minChunks: 1,
						chunks:    'all',
					},
					utils:   {
						test:      /[\\/]utils[\\/]/,
						name:      'utils',
						minSize:   0,
						minChunks: 1,
						chunks:    'all',
					},
				},
			},
		},
	};
};
